import { Component, OnInit, Input } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { ConfigService } from '../config.service';
import { ToastComponent } from '../toast/toast.component';
declare var $: any;
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [ConfigService]
})

export class LoginComponent implements OnInit {

  @Input('type') type: any;

  username: string = '';
  password: string = '';
  info: any;
  msg: any;
  constructor(public http: Http, public config: ConfigService) {

  }

  ngOnInit() {

  }

  closeLogin() {
    $('#modal1').modal('close');
  }

  tryLogin() {
    if (this.username == '' || typeof (this.username) == null) {
      this.info = '请输入用户名';
      return;
    }
    if (this.password == '' || typeof (this.password) == null) {
      this.info = '请输入密码';
      return;
    }
    this.Login();
  }

  Login() {
    let params = new URLSearchParams();
    params.set('telphone', this.username);
    params.set('password', this.password);
    this.http.post('http://www.damojiankang.cn/user/login_by_telphone', params).subscribe((res: any) => {
      let data = res.json();
      if (data.info && data.info.userinfo) {
        this.getUserinfo(data.info.userinfo.id);
        this.msg = '登陆成功';
        $('#modal1').modal('close');
      } else {
        this.msg = '密码错误或账号错误'
      }
    })
  }

  getUserinfo(uid: any) {
    let params = new URLSearchParams();
    params.set('uid', uid);
    this.http.post('http://api.damojiankang.cn/Home/user/ger_user_info', params).subscribe((res: any) => {
      let data = res.json();
      if (data) {
        this.config.userinfo = data;
        this.config.change_login();
      }
    })
  }

}
